package dataBase;

import java.util.ArrayList;

import net.ClientSystem;
import net.NetCommand;


public class DataBase_net extends DataBase {
	ClientSystem cs = new ClientSystem();

	@Override
	public boolean containsKey(String listName, String key) {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("containsKey " + listName + " "
					+ key, null);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (boolean) obj;
	}

	@Override
	public Data getData(String listName, String id) {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("getData " + listName + " " + id,null);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (Data) obj;
	}

	@Override
	public void putData(String listName, String id, Data d) {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("putData " + listName + " " + id,d);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if((int)obj == 0) {
			System.out.println("putData-OK");
		} else {
			System.out.println("putData-Fail");
		}
	}

	@Override
	public void deleteData(String listName, String id) {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("deleteData " + listName + " " + id,null);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if((int)obj == 0) {
			System.out.println("deleteData-OK");
		} else {
			System.out.println("deleteData-Fail");
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public ArrayList<? extends Data> getDataList(String listName) {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("getDataList " + listName,null);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (ArrayList<? extends Data>) obj;
	}

	public boolean initialize() {
		Object obj = null;
		try {
			NetCommand netCmd = new NetCommand("start",null);
			obj = cs.sentNetCmd(netCmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (obj == null) {
			System.out.println("Connection Failed!");
			return false;
		}
		if (((String) obj).equals("start")) {
			System.out.println("Connection Succeed!");
			return true;
		}
		return false;
	}
}
